import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:wk_robot2/app/utils/CommonUtil.dart';

import '../../../const/AppConst.dart';
import '../../../event/DataCallBack.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../routes/app_pages.dart';
import '../../../storage/StorageManager.dart';
import '../../../utils/NetWorkUtil.dart';
import '../../../widget/tips.dart';

class DismissAccountFianlController extends GetxController {

  var phoneNumber = ''.obs;
  var displayPhoneNumber = ''.obs;


  var countDown = 60.obs;
  var buttonText = '获取验证码'.obs;
  var buttonIsAble = true.obs;

  Timer? _timer;

  var validateCodeController = TextEditingController().obs;

  @override
  void onInit() {
    super.onInit();
    phoneNumber.value = CommonUtil.getLoginUser()['userPhone'];

    displayPhoneNumber.value = phoneNumber.value.substring(0,3) + "****" + phoneNumber.value.substring(phoneNumber.value.length - 4,phoneNumber.value.length);
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
    if (_timer != null) {
      _timer!.cancel();
    }
  }

  void startRequestValidateCode () async {
    if (!buttonIsAble.value) {
      return;
    }
    //做权限检查.
    bool isNetWork = await NetWorkUtil.checkNetWorkIsAvailable();
    if (!isNetWork) {
      Tips.showToast('网络不可用.');
      return;
    }

    // 请求接口,发送邮箱验证码.
    NetWorkManager.getInstance().requestBussiness(NetWorkManager.GET_MSG_VALIDATE_CODE, {
      'account': phoneNumber.value,
      'accountType': '0',
      'purpose': '3'

    }, NetWorkManager.methodGET, DataCallBack(
        businessCallBack: (data) {
          Tips.showToast('验证码已发送.');
          buttonIsAble.value = false;
          buttonText.value = countDown.value.toString() +"秒";

          _timer = Timer.periodic(Duration(seconds: 1), (timer) {
            if (countDown.value < 1) {
              timer.cancel();
              buttonIsAble.value = true;
              buttonText.value = '获取验证码';
              countDown.value = 60;

            } else {
              countDown.value = countDown.value - 1;
              buttonText.value = countDown.value.toString() +"秒";
            }
          });


        }
    ),showLoading: true);

  }


  void dismissUserAccount() {
      NetWorkManager.getInstance().requestBussiness(NetWorkManager.DISMISS_USER_ACCOUNT, {}, NetWorkManager.methodDELETE, DataCallBack(
          businessCallBack: (param) {
            StorageManager.getStorage().remove(AppConst.storage_key_login_token);
            StorageManager.getStorage().remove(AppConst.storage_current_login_user);
            Tips.showToast('账号已注销.');
            Get.offAllNamed(Routes.LOGIN);
          }
      ));

  }
}
